package bll

import (
	"context"
	"fmt"
	"gitlab.local/backend/pkg/cron"
	log "simcard/collector/logger"
	"simcard/errors"
	"simcard/model"
	"strings"
	"sync"
	"time"
)

var (
	PrepaidCron = &prepaidCron{
		Cron: cron.New(cron.WithLocation(time.Local), cron.WithSeconds()),
	}
)

type prepaidCron struct {
	*cron.Cron
}

func init() {
	Register(PrepaidCron)
}

func (a *prepaidCron) initLoadData() error {

	var (
		initCount = 1
		wp        = sync.WaitGroup{}
		logMsg    []string
	)

	wp.Add(initCount)

	go func() {
		err := a.checkRecharge()
		logMsg = append(logMsg, fmt.Sprintf("%+v", err))
		wp.Done()
	}()

	wp.Wait()
	return errors.New(strings.Join(logMsg, ","))
}

func (a *prepaidCron) init() func() {

	a.Start()
	var (
		scheduleJobList = []struct {
			Spec    string
			Comment string
			Desc    string
			cron.FuncJob
		}{
			{
				//Spec: "@every 30s",
				Spec: "@every 12h",
				//Spec:    "@weekly",
				Comment: "每周检查一次",
				Desc:    "检查预付费的表，是否有记录触发流量卡充值",
				FuncJob: a.CheckRecharge,
			},
		}
	)

	for _, v := range scheduleJobList {
		_, _ = a.AddFunc(v.Spec, v.FuncJob)
	}

	go func() {
		log.Info(fmt.Sprintf("%+v", a.checkRecharge()))
	}()

	return func() {}
}

func (a *prepaidCron) CheckRecharge(args ...interface{}) {

	log.Info(fmt.Sprintf("%+v", a.checkRecharge(args...)))
}

func (a *prepaidCron) checkRecharge(args ...interface{}) error {

	return Prepaid.CheckForDelayRepaid(context.Background(), &model.SimCardListRequest{})
}
